package com.ilovepostcard.view;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ilovepostcard.R;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.SimpleUser;
import com.ilovepostcard.model.User;

public class UserGridView extends LinearLayout {

    public static interface OnUserClickListener {
        void onClick(final SimpleUser user);
    }

    public static interface OnUserLongClickListener {
        void onLongClick(final SimpleUser user);
    }

    private OnUserClickListener mOnUserClickListener;

    private OnUserLongClickListener mOnUserLongClickListener;

    /* page index start from 1 */
    private int mPage = 0;

    private ArrayList<SimpleUser> mUsersList = new ArrayList<SimpleUser>();

    private UserGridAdapter mAdapter;

    private String mSource;

    private User loginUser;
    
    private View showMore;
    
    private TextView mEmpty;

    public UserGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.UserGridView);
        mSource = ta.getString(R.styleable.UserGridView_source);
        ta.recycle();
        inflate();
    }

    public UserGridView(Context context) {
        super(context);
        inflate();
    }

    public void setOnUserClickListener(OnUserClickListener onUserClickListener) {
        this.mOnUserClickListener = onUserClickListener;
    }

    public void setOnUserLongClickListener(OnUserLongClickListener onUserLongClickListener) {
        this.mOnUserLongClickListener = onUserLongClickListener;
    }
    
    public void removeUser(SimpleUser user) {
        mUsersList.remove(user);
        mAdapter.notifyDataSetChanged();
    }

    private int getEmpetyText() {
        if ("followed".equals(mSource)) {
            return R.string.empty_followed;
        } else if ("following".equals(mSource)) {
            return R.string.empty_following;
        }
        return R.string.empty_default;
    }
    
    private void inflate() {
        View view = View.inflate(getContext(), R.layout.user_grid_view, this);
        showMore = view.findViewById(R.id.user_show_more);
        GridView gridView = (GridView) view.findViewById(android.R.id.list);
        mAdapter = new UserGridAdapter();
        gridView.setAdapter(mAdapter);
        mEmpty = (TextView) view.findViewById(android.R.id.empty);
//        mEmpty.setText(getEmpetyText());
        gridView.setEmptyView(mEmpty);
        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mOnUserClickListener != null) {
                    SimpleUser user = mUsersList.get(position);
                    mOnUserClickListener.onClick(user);
                }
            }

        });
        gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (mOnUserLongClickListener != null) {
                    SimpleUser user = mUsersList.get(position);
                    mOnUserLongClickListener.onLongClick(user);
                    return true;
                }
                return false;
            }

        });
        showMore.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                loadNextPage();
            }
        });

    }

    public boolean isLoaded() {
        return mPage > 0;
    }
    
    public void loadNextPage() {
        if (loginUser == null)
            loginUser = UserController.getLoginUser(getContext());
        
        if (!isLoaded()) {
			showEmpty(false);
		}
        
        new ServerAsyncTask(getContext()) {

            @Override
            protected void onSuccess(PostcardResult result) {
                showEmpty(true);
                ArrayList<SimpleUser> users = result.getAttentionList();
                if (users == null || users.size() == 0) {
                    if(mPage>0)
                        Toast.makeText(context, "没有更多啦～", Toast.LENGTH_SHORT).show();
                    else
                        showMore.setVisibility(GONE);
                    mPage++;
                    return;
                }
                mPage++;
                mUsersList.addAll(users);
                if (mUsersList.size() > 0) {
                    showMore.setVisibility(VISIBLE);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            protected PostcardResult doRequest() {
                return ServerFactory.getServer().getAttentionList(loginUser.UserID,
                        "followed".equals(mSource) ? IServer.ATTENTION_FOLLOWED : IServer.ATTENTION_FOLLOWING,
                        (mPage + 1), 15);
            }
        }.execute();
    }
    
    private void showEmpty(boolean show) {
    	mEmpty.setText(show ? getContext().getString(getEmpetyText()) : "");
    }

    private class UserGridAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mUsersList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            UserWidget widget = null;
            if (convertView != null)
                widget = (UserWidget) convertView;
            else
                widget = new UserWidget(getContext());
            widget.setGravity(Gravity.CENTER);
            SimpleUser user = mUsersList.get(position);
            widget.setSimpleUser(user);
            return widget;
        }

    }
}
